package com.shire.web.console.controller.kf;

import com.shire.web.console.common.MD5Util;
import com.shire.web.console.common.Response;
import com.shire.web.console.model.user.SystemUser;
import com.shire.web.console.service.user.SystemUserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {
    @Resource
    private SystemUserService systemUserService;

    @RequestMapping("/")
    public String index(HttpSession session){
        if (session.getAttribute("user")!=null){
            return "redirect:/kf/manage";
        }else {
            return "redirect:/login";
        }
    }

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public Response checkAuth(@RequestBody SystemUser user, HttpSession session){
        Response response = new Response();

        try {
            SystemUser authUser = systemUserService.checkLogin(user.getUserName(),MD5Util.MD5Encode(user.getPassword()));
            if (authUser != null){
                session.setAttribute("user",authUser);
                Map<String , Integer> map = new HashMap<>();
                map.put("userType", authUser.getIsKf());
                response.setData(map);
                response.success("操作成功");
            }else {
                response.error("用户名或密码错误！");
            }

        }catch (Exception e){
            response.error("接口错误: "+e.getMessage());
            e.printStackTrace();
        }
        return response;
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:login";
    }
}
